package org.bdware.irs.server.http;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class IRSMockMain {

    static LocalHandler localHandler;
    static Logger logger = Logger.getLogger(IRSMockMain.class);
    static int port = 10001;

    public static void main(String[] arg) throws Exception {
        localHandler = new LocalHandler();
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/test", new TestHandler());
        server.createContext("/resolve", new ResolveHandler());
        server.createContext("/local/", localHandler);
        server.start();
    }

    static class TestHandler implements HttpHandler{
        @Override
        public void handle(HttpExchange exchange) {
            String response = "hello world";
            try{
                exchange.sendResponseHeaders(200,0);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class ResolveHandler implements HttpHandler{
        @Override
        public void handle(HttpExchange exchange) {
            try{
                //获得查询字符串(get)
                String queryString =  exchange.getRequestURI().getQuery();
                Map<String,String> queryStringInfo = formData2Dic(queryString);
                Map<String,String> respMap;
                respMap = localHandler.handleResolve(queryStringInfo);

                for (String key: respMap.keySet()){
                    logger.debug(String.format("Key:%s; Value:%s\n",key,respMap.get(key)));
                }
                JSONObject jsonObj=new JSONObject(respMap);
                exchange.getResponseHeaders().add("Access-Control-Allow-Origin","*");
                exchange.sendResponseHeaders(200,0);
                OutputStream os = exchange.getResponseBody();
                os.write(jsonObj.toString().getBytes());
                os.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static Map<String,String> formData2Dic(String formData ) {
        Map<String,String> result = new HashMap<>();
        if(formData== null || formData.trim().length() == 0) {
            return result;
        }
        final String[] items = formData.split("&");
        Arrays.stream(items).forEach(item ->{
            final String[] keyAndVal = item.split("=");
            if( keyAndVal.length == 2) {
                try{
                    final String key = URLDecoder.decode( keyAndVal[0],"utf8");
                    final String val = URLDecoder.decode( keyAndVal[1],"utf8");
                    result.put(key,val);
                }catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
        return result;
    }

}